const websocket = require('ws')
const handleMsg = require('../utils/handleMessage')

const port = 9092
const wss = new websocket.Server({
  port
})

// 存储所有连接的客户端
const clients = new Map()

const listen = () => {
  wss.on('connection', (ws, req) => {
    const params = new URLSearchParams(req.url.split('?')[1])
    const user_id = params.get('user_id')
    console.log(`${user_id} 已连接`)
    clients.set(user_id, ws)

    // 心跳检测变量
    let isAlive = true
    
    // 心跳检测定时器
    const heartbeatInterval = setInterval(() => {
      if (!isAlive) {
        console.log('心跳检测失败，终止连接')
        return ws.terminate()
      }
      
      isAlive = false
      ws.ping()
    }, 30000) // 30秒检测一次

    // 处理消息
    ws.on('message', (message) => {
      const data = JSON.parse(message)
      // console.log(data)
      if (data.type === 'message') {
        handleMsg.setMsgtoDB(data, (res) => {
          // 存入数据库后做些什么
          if (res.code === 200) {
            // 给信息发送者
            ws.send(JSON.stringify({
              code: res.code,
              message: res.message,
              type: 'message',
              data: res.data
            }))

            // 给信息接收者
            const receiver = clients.get(res.data.receiver_id)
            if (!receiver) return
            receiver.send(JSON.stringify({
              code: res.code,
              message: res.message,
              type: 'message',
              data: res.data
            }))
          }
        })
      }
      
      // 处理心跳消息
      if (data.type === 'heart beat') {
        isAlive = true
        ws.send(JSON.stringify({
          code: 200,
          type: 'heart beat ack'
        }))
        return
      }
    })

    // 处理关闭事件
    ws.on('close', () => {
      console.log(`${user_id} 断开连接`)
      clearInterval(heartbeatInterval)
      clients.delete(ws)
    })

    // 处理错误
    ws.on('error', (error) => {
      console.error('WebSocket错误:', error)
    })
  })
}

module.exports = {
  listen,
  clients
}
